﻿/**
 * Reboulder - Partial Boulder Dash clone
 * Jesús Sagra, 2014
 * 
 * HiScores class: manages highest scores
 * 
 * Version    Date     Changes
 * -----------------------------------------------------
 *  0.01   06-mar-2015  Constructor, Getters, SetHiScore
 */

using System;
using System.IO;

class HiScores
{
    public struct Score
    {
        public int points;
        public string name;
        public string place;
    }
    public Score[] scores = new Score[10];

    public HiScores()
    {
        //TO DO check if exist,try,cath 

        string line;
        StreamReader hiScoresFile = File.OpenText("HiScores.txt");

        for (int i = 0; i < scores.Length; i++)
        {
            line = hiScoresFile.ReadLine();
            scores[i].place = line.Substring(0,4);
            scores[i].name = line.Substring(5,3);
            scores[i].points = Convert.ToInt32(line.Substring(9));
        }
        hiScoresFile.Close();
    }


    // Checks whether to save the new record
    public void SetHiScore(int score)
    {
        if(score > scores[9].points)
        {
            //TO DO
            //Improve method and change i j k variables

            // Seeks the position where to insert the new record
            byte insertPos = 0;
            while (score <= scores[insertPos].points)
            {
                insertPos++;
            }

            // Inserts the new record into its position
            for (int j = scores.Length-1; j > insertPos; j--)
            {
                scores[j].points = scores[j - 1].points;
                scores[j].name = scores[j - 1].name;
            }
            scores[insertPos].points = score;
            scores[insertPos].name = "---";

            // Write the new file records
            StreamWriter newHiScoreFile = new StreamWriter("HiScores.txt");
            for (int k = 0; k < scores.Length; k++)
            {
                newHiScoreFile.WriteLine(scores[k].place + " " +
                    scores[k].name + " " + scores[k].points);
            }
            newHiScoreFile.Close();
        }
    }
}